<!--
 * @Author: wangming
 * @Date: 2021-06-10 11:11:51
 * @LastEditors: wangming
 * @LastEditTime: 2022-05-30 09:52:12
 * @Description: file content
-->
<template>
  <el-input
    v-if="isEdit"
    :style="{
      width: config.__config.width + '%',
    }"
    :placeholder="config.__config.placeholder"
  />
  <tree-select
    v-else
    :fieldMap="fieldMap"
    clearable
    :disabled="disabled"
    filterable
    :value="datas"
    :multiple="config.__config.multiple"
    :placeholder="config.__config.placeholder"
    @change="changes"
    :treeData="treeData"
    :style="{
      width: config.__config.width + '%',
    }"
    valueString
    :filterNodeMethod="filterNodeMethod"
    :readOnly="viewInfo"
  >
  </tree-select>
</template>

<script>
import myMixin from "@/pageComponents/myMixin";
import vmMixin from "@/pageComponents/vmMixin";
import { cloneDeep, merge } from "lodash";
import { postHmhttprequestdefinitionExecute } from "@/apis/paas/HmHttpRequestDefinitionController.js";
import { dataToList } from "@/utils/util";
import { getVueComponent } from "@/utils/common.js";
export default {
  mixins: [myMixin, vmMixin],
  vmEvents: {
    reload() {
      this.treeData = [];
      this.getTree();
    },
    disabledNode(code) {
      let id = this.getCode(code);
      const tree = cloneDeep(this.treeData);
      this.transformTreeDisabled(tree, id ? `[${id}]` : null);
      this.treeData = tree;
    },
    addSearchData(queryData) {
      this.queryData = merge({}, this.queryData, queryData);
    },
    getTreeNodeById(id) {
      return this.getTreeNodeById(this.getCode(id));
    },
    async setData(treeData) {
      this.treeData = treeData;
    },
  },

  mounted() {
    if (this.isEdit) return;
    this.getTree();
  },
  data() {
    return {
      queryData: {
        modelKey: this.config.__config.modelCode,
        key: "selectTree",
        values: {
          _TREE_NODE_DISPLAY_RULE_: this.config.__config.valueTeam,
        },
      },
      datas: "",
      treeData: [],
      fieldMap: {
        value: "uniqueKey", // value 对应的字段
        label: "label", // label 对应的字段 同时支持作用域插槽
        disabled: "disabled",
      },
    };
  },
  watch: {
    value: {
      handler: "def",
      immediate: true,
    },
  },
  computed: {
    dataLoadFunction() {
      const { dataCustomLoadFn } = this.config.__config;
      return getVueComponent(dataCustomLoadFn);
    },
  },
  methods: {
    getCode(id) {
      let code = id + "";
      return code.replace(/\[|\]/g, "");
    },
    getTreeNodeById(id) {
      let queen = [],
        node = null;
      queen = queen.concat(this.treeData);
      while (queen.length) {
        let first = queen.shift();
        let { values } = first;
        if (values.id == id) {
          node = first;
        } else if (first.children) {
          queen = [].concat(first.children, queen);
        }
      }
      return node;
    },
    filterNodeMethod(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    transformTreeDisabled(tree, id) {
      tree.forEach((i) => {
        i.disabled = id
          ? i.values.parent_ids.indexOf(id) > -1 || `[${i.uniqueKey}]` == id
          : true;
        if (i.children.length > 0) {
          this.transformTreeDisabled(i.children, id);
        }
      });
    },
    async getTree() {
      const { dataCustomLoad, dataCustomLoadFn } = this.config.__config;
        if (dataCustomLoad && dataCustomLoadFn) {
          let options = await this.dataLoadFunction(
            this.vmEvents?.context,
            this.vmEvents?.exports,
            this.queryData
          );
          this.treeData = this.TransformTree(dataToList(options));
        } else if (this.queryData.modelKey) {
          const tree =
            (await postHmhttprequestdefinitionExecute(this.queryData, {
              useCache: true,
            })) || [];
          if (Object.prototype.toString.call(tree) === "[object Object]") {
            this.treeData = [tree];
          } else {
            this.treeData = tree || [];
        }
      }
    },
    TransformTree(list) {
      return list.map((i) => {
        i.uniqueKey = i.id || i?.values?.id;
        if (i?.children?.length > 0) {
          i.children = this.TransformTree(i.children);
        } else {
          delete i.children;
        }
        return i;
      });
    },
    async changes(v) {
      if (this.config.__config.multiple) {
        this.$emit("input", (v || []).map((item) => `[${item}]`).join(""));
      } else {
        if (this.config.__config.codeType === "RELATION_REFERENCE") {
          this.$emit("input", v || "");
        } else {
          this.$emit("input", v ? `[${v}]` : "");
        }
      }
      await this.$nextTick();
      this.runEventName("change");
    },
    def() {
      let value;
      if (this.value) {
        value = (this.value + "").match(/[\w\u4e00-\u9fa5-]+/g);
      }
      if (this.config.__config.multiple) {
        this.datas = value || [];
      } else {
        this.datas = value ? value[0] : "";
      }
    },
  },
};
</script>

<style lang="scss" scoped></style>
